package com.saybiu.controller;

import com.alibaba.fastjson.JSONObject;
import com.saybiu.dao.UserDao;
import com.saybiu.dao.UserMetaDao;
import com.saybiu.domain.User;
import com.saybiu.domain.UserMeta;
import com.saybiu.exception.ServiceException;
import com.saybiu.response.ApiResult;
import com.saybiu.response.CommonCode;
import com.saybiu.service.UserService;
import com.saybiu.utils.JedisUtils;
import com.saybiu.utils.JwtUtil;
import com.saybiu.utils.TencentSmsUtil;
import com.saybiu.utils.WechatDecryptDataUtil;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author wangwei
 * @Date 2021/4/20 16:32
 * @Version 1.0
 */
@RestController
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 发送验证码
     */
    @PostMapping(value = "/sms")
    public void sms(String phoneNum)
    {

        JSONObject jsonObject = TencentSmsUtil.complete(phoneNum);
        if(jsonObject!=null)
        {
            if(jsonObject.getString("Code").equals("Ok"))
            {

            }
        }
        throw new ServiceException(CommonCode.FAIL,"短信发送失败,请检查后再次发送");
    }
    /*//注册用户
    @PostMapping(value = "/users/")
    public ApiResult add(@RequestBody User user){
        //手机号  注册时间  注册ip
        //userDao.
        return new ApiResult(CommonCode.SUCCESS,"创建用户成功");
    }*/
    @GetMapping(value="/users/getSessionKey")
    public ApiResult sessionKey(String code) {

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxdaf9d8a433d5fc06&secret=8ee4b531a9acb35c07875bb9310b7533&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        try {
            ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(forEntity.getBody());
            System.out.println(jsonObject.getString("errcode"));
            if (jsonObject.getString("errcode") == null) {
                return new ApiResult(CommonCode.SUCCESS,jsonObject);
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        throw new ServiceException(CommonCode.FAIL,"请求失败");
    }

    /**
     * 微信拉取电话号码(注册或者登录)
     * @param encryptedData
     * @param iv
     * @param sessionKey
     */
    @RequestMapping(value="/users/wxLogin")
    public void wxLogin(String encryptedData,String iv,String sessionKey)
    {

        if(encryptedData!=null&&iv!=null&sessionKey!=null&&!encryptedData.equals("")&&!iv.equals("")&&!sessionKey.equals("")){
            String jsonString = WechatDecryptDataUtil.decryptData(encryptedData, sessionKey,iv);
            //拿到电话号码
            String phoneNumber = JSONObject.parseObject(jsonString).getString("phoneNumber");
            //数据库判断电话号码是否存在
            //存在给token
            //不存在,注册并给token
        }
    }


    /**
     * 通过userid修改用户密码(可为null)或者电话(可为null)(user对象)
     * 通过userid修改用户属性信息(userMeta对象)
     * 前端封装为json字符串
     * @param jsonObject json对象
     * @return
     */
    @PutMapping(value = "/users/")
    public void updateUserOrUsermeta(@RequestBody JSONObject jsonObject){
        //解析json
        User user = jsonObject.getObject("user", User.class);
        UserMeta userMeta = jsonObject.getObject("userMeta", UserMeta.class);
        //判断对象类型
        if (user!=null){
            //修改用户密码和电话(用户表)
            userService.updatePhoneOrPassword(user);
        }else if(userMeta!=null){
            //修改用户个人信息(用户属性表)
            userService.updateUserMeta(userMeta);
        }
    }
    /**
     *  关注他人
     * 传入 被关注人id
     * @param beSupportedUserId 被关注人id
     * @return
     */
    @RequestMapping(value = "/users/",method = RequestMethod.POST)
    public void addSupport(Integer beSupportedUserId,Integer userId){
        //System.out.println("token"+userId);
        //userid从token中获取
        userService.addUserSupportAndUserBeSupported(userId,beSupportedUserId);
    }

    /**
     * 取消关注
     * @param beSupportedUserId  被关注人的id
     * @return
     */

    @DeleteMapping(value ="/users/{beSupportedUserId}")
    public void deleteSupport(@PathVariable("beSupportedUserId") Integer beSupportedUserId,Integer userId){
        //token解析userid
        //调用删除关注关系
        userService.deleteUserSupportAndUserBeSupported(userId,beSupportedUserId);
    }


    /**
     * 查询信息(通过userid)
     * 查询别人信息需要传对方id(get方式)
     * @param beSelectedUserId 被查询人id
     * @param userId 用户自己id
     */
    @GetMapping(value = "/users/{beSelectedUserId}")
    public User selectUser(@PathVariable("beSelectedUserId")Integer  beSelectedUserId,Integer userId){
        //查询用户信息(别人)
        User user = userService.queryUser(beSelectedUserId);
        return user;
    }

    //查询用户信息(userid查user)
    /**
     * 查询自己信息
     *  查询自己信息直接token解析id
     * @param userId
     */
    @GetMapping(value = "/users")
    public User selectUserself(Integer userId){
        //查询用户信息(自己)
        User user = userService.queryUser(userId);
        return user;
    }


}
